#!/usr/bin/env python3
# 读取本地长文（.txt / .md），作为 context 注入 -> 生成播客（Piper）
# 用法：
#   ./scripts/run_C_doc.py --doc data/knowledge/胜讯2025财报.md \
#                          --topic "胜讯2025财报：亮点、风险与趋势" \
#                          --roles configs/roles_piper.yaml --minutes 4 \
#                          --outdir output_C

import argparse, os, io, sys
# === 关键修复：把 src/ 放进 sys.path ===
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJ_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, ".."))
SRC_DIR = os.path.join(PROJ_ROOT, "src")
if SRC_DIR not in sys.path:
    sys.path.insert(0, SRC_DIR)

from llm_client import LLMClient, Role
from tts_client import TTSClient, Speaker
from audio_utils import concat_wavs_ffmpeg, to_mp3_ffmpeg
import yaml

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--doc", required=True, help="本地 .txt/.md 文件路径")
    ap.add_argument("--topic", required=True)
    ap.add_argument("--roles", default="configs/roles_piper.yaml")
    ap.add_argument("--minutes", type=int, default=4)
    ap.add_argument("--outdir", default="output_C")
    args = ap.parse_args()

    os.makedirs(args.outdir, exist_ok=True)

    # 1) 读文档
    with io.open(args.doc, "r", encoding="utf-8") as f:
        context = f.read()[:12000]  # 控长

    # 2) 角色/音色
    cfg = yaml.safe_load(open(args.roles, "r", encoding="utf-8"))
    roles = [Role(r["name"], r.get("style", "")) for r in cfg["roles"]]
    spks = [Speaker(name=r["name"], backend="piper",
                    model_path=r.get("model_path"),
                    config_path=r.get("config_path"),
                    sample_rate=int(r.get("sample_rate", 22050)),
                    sentence_silence=float(r.get("sentence_silence", 0.5)),
                    tts_params=r.get("tts") or {}) for r in cfg["roles"]]

    # 3) 生成脚本（深度风格）
    client = LLMClient()
    script = client.generate_dialogue(topic=args.topic, roles=roles,
                                      minutes=args.minutes, mode="deep",
                                      context=context)

    # 4) 保存脚本 & 合成
    with open(os.path.join(args.outdir, "script.txt"), "w", encoding="utf-8") as f:
        f.write(script)

    tts = TTSClient(spks, os.path.join(args.outdir, "tts"))
    segs = tts.synthesize_dialogue(script, os.path.join(args.outdir, "tts"))

    wav = concat_wavs_ffmpeg(segs, os.path.join(args.outdir, "podcast.wav"))
    mp3 = to_mp3_ffmpeg(wav, os.path.join(args.outdir, "podcast.mp3"))
    print("[OK] 长文播客：", wav, mp3)

if __name__ == "__main__":
    main()
